<template>
  <div class="app-container">
    <div v-if="isSearchBtn" class="filter-container">
      <el-input v-model="listQuery.title" placeholder="关键字" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>

    </div>
    <div style="background: #FFFFFF;padding: 0.625rem;">
      <div style="margin-bottom: 0.625rem;height: 2.5rem;">
        <el-button v-permission="'permission@add'" class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
        <el-button class="filter-item" plain icon="el-icon-sort" @click="expandTable">
          展开/折叠
        </el-button>
        <el-button circle style="float: right;" icon="el-icon-search" @click="showBtn" />
        <el-button circle style="float: right;" icon="el-icon-refresh" @click="getList" />
      </div>
      <el-table
        v-if="refreshTable"
        ref="dataTable"
        v-loading="listLoading"
        :data="list"
        :header-cell-style="{background:'#eee',color:'#606266'}"
        fit
        highlight-current-row
        style="width: 100%;"
        row-key="id"
        show-header
        :default-expand-all="tableExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >

        <el-table-column label="菜单名称" width="160px" align="left">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleUpdate(row)">{{ row.permission_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="图标" width="60px" align="center">
          <template slot-scope="{row}">
            <i :class="row.icon" />
          </template>
        </el-table-column>
        <el-table-column label="路由Path" width="180px" align="left">
          <template slot-scope="{row}">
            <span>{{ row.route }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限标识" width="170px" align="left">
          <template slot-scope="{row}">
            <span>{{ row.permission_mark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="130px" align="left">
          <template slot-scope="{row}">
            <el-tag
              v-if="row.type===1"
              type=""
              effect="dark"
            >
              导航菜单
            </el-tag>
            <el-tag
              v-if="row.type===2"
              type="success"
              effect="dark"
            >
              按钮菜单
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="60px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" class-name="status-col" width="200">
          <template slot-scope="{row}">
            <el-switch
              v-permission="'permission@show'"
              :value="row.hidden===0?'0':'1'"
              active-text="启用"
              inactive-text="禁用"
              active-value="0"
              inactive-value="1"
              @change="isShow(row.hidden,row.id,row)"
            />

          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="155px">
          <template slot-scope="{row}">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="130" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button v-permission="'permission@edit'" title="编辑" type="primary" icon="el-icon-edit" circle @click="handleUpdate(row)" />
            <el-button v-if="row.status!=='deleted'" v-permission="'permission@del'" title="删除" icon="el-icon-delete" circle type="danger" @click="handleDelete(row,$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px">
        <div class="el-col el-col-12">
          <el-form-item label="父级菜单" prop="parent_id">
            <el-cascader
              v-model="temp.parent_id"
              style="width:90%"
              size="medium"
              :options="cascaderData"
              :props="{ checkStrictly: true }"
              clearable
              @change="cascaderCheck"
            />
          </el-form-item>
        </div>
        <div class="el-col el-col-12">
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="temp.type" @input="typeChange">
              <el-radio-button label="1">菜单</el-radio-button>
              <el-radio-button label="2">按钮</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="el-col el-col-12">
          <el-form-item label="菜单名称" prop="permission_name">
            <el-input v-model="temp.permission_name" placeholder="请输入2-100字符的菜单名称" />
          </el-form-item>
        </div>
        <div class="el-col el-col-12">
          <el-form-item label="权限标识" prop="permission_mark">
            <el-input v-model="temp.permission_mark" placeholder="请输入2-120字符的权限标识" />
          </el-form-item>
        </div>
        <div v-if="isShowForm" class="el-col el-col-12">
          <el-form-item label="模块" prop="module">
            <el-input v-model="temp.module" placeholder="请输入模块名称" />
          </el-form-item>
        </div>
        <div v-if="isShowForm" class="el-col el-col-12">
          <el-form-item label="菜单图标" prop="icon">
            <el-input v-model="temp.icon" placeholder="请输入菜单图标" />
          </el-form-item>
        </div>
        <div v-if="isShowForm" class="el-col el-col-12">
          <el-form-item label="菜单Path" prop="route">
            <el-input v-model="temp.route" placeholder="请输入菜单Path" />
          </el-form-item>
        </div>
        <div v-if="isShowForm" class="el-col el-col-12">
          <el-form-item label="组件路径" prop="component">
            <el-input v-model="temp.component" placeholder="请输入组件路径" />
          </el-form-item>
        </div>
        <div v-if="isShowForm" class="el-col el-col-12">
          <el-form-item label="Redirect" prop="redirect">
            <el-input v-model="temp.redirect" placeholder="请输入Redirect" />
          </el-form-item>
        </div>
        <div v-if="isShowForm" class="el-col el-col-12">
          <el-form-item label="Keepalive" prop="keepalive">
            <el-radio v-model="temp.keepalive" label="1">开启</el-radio>
            <el-radio v-model="temp.keepalive" label="2">关闭</el-radio>
          </el-form-item>
        </div>
        <div v-if="isShowForm" class="el-col el-col-12">
          <el-form-item label="Hidden" prop="hidden">
            <el-radio v-model="temp.hidden" label="0">显示</el-radio>
            <el-radio v-model="temp.hidden" label="1">隐藏</el-radio>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getData, getAll, permissionDisable, permissionEnable, createPermission, updatePermission, delPermission } from '@/api/permission'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission'
import { parseTime } from '@/utils'

const calendarTypeOptions = [
  { key: '1', display_name: '导航菜单' },
  { key: '2', display_name: '按钮菜单' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PermissionRules',
  // components: { Pagination },
  directives: { waves, permission },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      calendarTypeOptions,
      tableExpandAll: false,
      cascaderData: [],
      isSearchBtn: false,
      statusOptions: ['启用', '禁用'],
      refreshTable: true,
      isShowForm: true,
      listQuery: {
        p: 1,
        limit: 10,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      temp: {
        id: undefined,
        permission_name: '',
        parent_id: 0,
        keepalive: '1',
        type: '1',
        hidden: '0',
        redirect: '',
        is_hid: '0'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        permission_name: [{ required: true, message: '菜单名称必填', trigger: 'change' }],
        permission_mark: [{ required: true, message: '权限标识必填', trigger: 'change' }],
        module: [{ required: true, message: '模块必选', trigger: 'change' }]
      },
      isShowSwitch: ''
    }
  },
  created() {
    this.getList()
    this.getAll()
  },
  methods: {
    expandTable() {
      this.refreshTable = false
      this.tableExpandAll = !this.tableExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    typeChange: function(params) {
      if (params === '1') {
        this.isShowForm = true
      } else {
        this.isShowForm = false
      }
    },
    showBtn() {
      if (this.isSearchBtn === false) {
        this.isSearchBtn = true
      } else {
        this.isSearchBtn = false
      }
    },
    getAll() {
      getAll().then(response => {
        this.cascaderData = response.data
      })
    },
    getList() {
      this.listLoading = true
      getData(this.listQuery).then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    isShow(isShow, id, row) {
      const data = {}
      data.ids = id
      if (isShow === false) {
        permissionDisable(data).then(response => {
          row.is_hid = '1'
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      } else {
        permissionEnable(data).then(response => {
          row.is_hid = '0'
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      }
    },
    cascaderCheck: function(data) {
      this.temp.parent_id = data[data.length - 1]
      this.temp.level = data.split('-')
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        permission_name: '',
        parent_id: 0,
        keepalive: '1',
        hidden: '0',
        redirect: '',
        type: '1',
        is_hid: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createPermission(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.hidden = this.temp.hidden.toString()
      this.temp.keepalive = this.temp.keepalive.toString()
      this.dialogStatus = 'update'
      if (this.temp.type === 1) {
        this.isShowForm = true
      } else {
        this.isShowForm = false
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updatePermission(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    resetQuery() {
      this.listQuery = {
        p: 1,
        limit: 10,
        title: undefined,
        type: undefined,
        sort: '+id'
      }
      this.getList()
    },
    handleDelete(row, index) {
      const tempData = {}
      tempData.ids = row.id
      delPermission(tempData).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
        this.getList()
      })
    },
    handleFilter() {
      this.listQuery.p = 1
      this.getList()
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style>
  .filter-item{
    margin-right: 0.3125rem;
  }
</style>
